package com.ruoyi.system.outto.game.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.exception.GlobalException;
import com.ruoyi.common.utils.SecuritySHA1Utils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.http.HttpUtils;
import com.ruoyi.system.model.domain.AccountInfo;
import com.ruoyi.system.model.domain.InfoImg;
import com.ruoyi.system.model.domain.SalePartner;
import com.ruoyi.system.model.mapper.AccountInfoMapper;
import com.ruoyi.system.model.mapper.InfoImgMapper;
import com.ruoyi.system.outto.core.LCConstant;
import com.ruoyi.system.outto.core.MapUntils;
import com.ruoyi.system.outto.core.OutUrlConstant;
import com.ruoyi.system.outto.dto.LDConstant;
import com.ruoyi.system.outto.game.CommonApi;
import com.ruoyi.system.outto.game.LDAPI;
import com.ruoyi.system.outto.game.LDV2API;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.collections4.CollectionUtils;
import org.omg.CORBA.TIMEOUT;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author lz
 * @version 1.0
 * @date 2022/6/5 16:19
 */
@Slf4j
@Service
public class LDV2APIImpl implements LDV2API {

    @Resource
    private InfoImgMapper infoImgMapper;
    @Value("${desc.title}")
    private String descTitle;
    //    private SalePartner salePartner;
    @Resource
    private CommonApi commonApi;

    @Resource
    private AccountInfoMapper accountInfoMapper;


    @Override
    public AjaxResult addGame(AccountInfo accountInfo, Long userId, SalePartner salePartner) {

        String path = "api/goods/platform/release";
//        this.salePartner = salePartner;
        Map<String, Object> result = new HashMap<>();
        Map<String, Object> params = params(accountInfo, salePartner);
        log.info("老达代售添加接口请求参数={}", params);
        String response = HttpUtils.doPostForm(salePartner.getTwoOther() + path, params, null);
        log.info("老达代售添加接口返回参数={}", response);
        JSONObject resultJson = JSONObject.parseObject(response);
        if (!"1".equals(resultJson.getString("code"))) {
            result.put("code", 500);
        } else {
            result.put("code", 200);
//            {"code":1,"msg":"添加成功","time":1677939248,"data":{"id":"54554"}}
            String data = resultJson.getString("data");
            if (StringUtils.isNotEmpty(data)) {
                JSONObject jsonObject = JSON.parseObject(data);
                String product_id = jsonObject.getString("id");

                AccountInfo info = accountInfoMapper.selectAccountInfoById(accountInfo.getId());
                info.setLdvt(product_id);
                accountInfoMapper.updateAccountInfo(info);

                String rand_str = rand_str();
                Map<String, Object> paramsUp = new LinkedHashMap<>();
                paramsUp.put("appid", salePartner.getSaleKey());
                paramsUp.put("secret", salePartner.getOther());
                paramsUp.put("rand_str", rand_str);
                paramsUp.put("timestamp", new Date().getTime() / 1000);
                String cover = MapUntils.getCover(paramsUp);
                cover = cover.substring(0, cover.length() - 1);
                log.info("cover={}", cover);
                String sign = DigestUtils.md5Hex(cover);
                String sr = sign + rand_str;
                try {
                    sr = SecuritySHA1Utils.shaEncode(sr);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                paramsUp.put("sign", sr);

                paramsUp.put("id", accountInfo.getLdid());
                String pathUp = "api/goods/platform/upper";

                log.info("老达上架接口请求参数={}", JSONObject.toJSONString(params));
                HttpUtils.doPostForm(salePartner.getTwoOther() + pathUp, params, null);
                if (StringUtils.isEmpty(response)) {
                    throw new GlobalException("请求接口失败");
                }
                log.info("老达上架接口返回参数={}", JSONObject.toJSONString(response));
            }
        }

        result.put("req", JSONObject.toJSONString(params));
        result.put("res", response);
        result.put("msg", resultJson.getString("data"));

        return AjaxResult.success(result);
    }

    @Override
    public AjaxResult editGame(AccountInfo accountInfo, Long userId, SalePartner salePartner) {
        String path = "api/goods/platform/release";
//        this.salePartner = salePartner;
        Map<String, Object> result = new HashMap<>();
        Map<String, Object> params = params(accountInfo, salePartner);
        log.info("老达编辑接口请求参数={}", JSONObject.toJSONString(params));
        String response = HttpUtils.doPostForm(salePartner.getTwoOther() + path, params, null);
        log.info("老达编辑接口返回参数={}", response);
        JSONObject resultJson = JSONObject.parseObject(response);

        if (!"1".equals(resultJson.getString("code"))) {
            result.put("code", 500);
        } else {
            result.put("code", 200);
        }


        result.put("req", JSONObject.toJSONString(params));
        result.put("res", response);
        result.put("msg", resultJson.getString("data"));
        return AjaxResult.success(result);
    }


    private Map<String, Object> params(AccountInfo accountInfo, SalePartner salePartner) {

        String rand_str = rand_str();
        Map<String, Object> params = new LinkedHashMap<>();
        params.put("appid", salePartner.getSaleKey());
        params.put("secret", salePartner.getOther());
        params.put("rand_str", rand_str);
        params.put("timestamp", new Date().getTime() / 1000);
        String cover = MapUntils.getCover(params);
        cover = cover.substring(0, cover.length() - 1);
        log.info("cover={}", cover);
        String sign = DigestUtils.md5Hex(cover);
        String sr = sign + rand_str;
        try {
            sr = SecuritySHA1Utils.shaEncode(sr);
        } catch (Exception e) {
            e.printStackTrace();
        }
        params.put("sign", sr);

        params.put("id", accountInfo.getLdvt());
        params.put("code", accountInfo.getId());
        String regional = accountInfo.getRegional();

        JSONObject property = new JSONObject();

        if (Objects.equals("王者荣耀", accountInfo.getType())) {

            params.put("game_id", 663);

            if (Objects.equals("安卓Q", regional)) {
                params.put("server_id", 70582);
            } else if (Objects.equals("安卓WX", regional)) {
                params.put("server_id", 71058);
            } else if (Objects.equals("苹果WX", regional)) {
                params.put("server_id", 71536);
            } else if (Objects.equals("苹果Q", regional)) {
                params.put("server_id", 71402);
            }
            property.put("f1", "我是号主");
            if (Arrays.asList(LCConstant.haveTwoList).contains(accountInfo.getLevel())) {
                property.put("f2", "可二次实名");
            } else if (LCConstant.bakFace.equals(accountInfo.getLevel())) {
                property.put("f2", "包人脸");
            } else {
                property.put("f2", "不可二次实名");
            }

            property.put("f3", "荣耀黄金");
            property.put("f4", "无");
            property.put("f5", accountInfo.getCampId());
            property.put("f6", accountInfo.getHeroes());
            property.put("f7", accountInfo.getSkins());

        }
        if (Objects.equals("和平精英", accountInfo.getType())) {
            params.put("game_id", 204);

            if (Objects.equals("安卓Q", regional)) {
                params.put("server_id", 23401);
            } else if (Objects.equals("安卓WX", regional)) {
                params.put("server_id", 23404);
            } else if (Objects.equals("苹果WX", regional)) {
                params.put("server_id", 23410);
            } else if (Objects.equals("苹果Q", regional)) {
                params.put("server_id", 23407);
            }

            property.put("f1", "我是号主");
            if (Arrays.asList(LCConstant.haveTwoList).contains(accountInfo.getLevel())) {
                property.put("f2", "能二次实名");
            } else if (LCConstant.bakFace.equals(accountInfo.getLevel())) {
                property.put("f2", "包人脸");
            } else {
                property.put("f3", "不能二次实名");
            }

            property.put("f5", accountInfo.getSuit());
            property.put("f6", accountInfo.getGuns());
        }
        if (Objects.equals("永劫无间", accountInfo.getType())) {
            params.put("game_id", 813);

            if (Objects.equals("网易", regional)) {
                params.put("server_id", 92475);
            } else if (Objects.equals("Steam", regional)) {
                params.put("server_id", 92477);
            }

            property.put("f1", "手机账号");

            property.put("f2", accountInfo.getHeroes());
            property.put("f3", accountInfo.getSkins());
        }
        if (Objects.equals("CF端游", accountInfo.getType())) {
            params.put("game_id", 59);

            String cf = LDConstant.cf;
            JSONObject jsonObject = JSONObject.parseObject(cf);
            String data = jsonObject.getString("data");
            List<JSONObject> jsonObjects = JSONObject.parseArray(data, JSONObject.class);
            for (JSONObject object : jsonObjects) {
                String name = object.getString("name");
                if (Objects.equals(name, regional)) {
                    String servers = object.getString("servers");
                    List<JSONObject> serversList = JSONObject.parseArray(servers, JSONObject.class);
                    for (JSONObject server : serversList) {
                        String name1 = server.getString("name");
                        name1 = name1.substring(0, 2);
                        if (accountInfo.getDes().contains(name1)) {
                            String id = server.getString("id");
                            params.put("server_id", id);
                        }
                    }
                }
            }

            property.put("f1", accountInfo.getRegional());

            property.put("f2", "是");
            property.put("f3", accountInfo.getSkins());

        }
        if (Objects.equals("原神", accountInfo.getType())) {
            params.put("game_id", 809);
            if (Objects.equals("官服", regional)) {
                property.put("f1", "官服-天空岛服");
                params.put("server_id", 92461);
            }
            if (Objects.equals("B服", regional)) {
                params.put("server_id", 92464);
                property.put("f1", "B服-世界树服");
            }
            if (!accountInfo.getRegional().equals("邮箱可换绑")) {
                property.put("f2", "死邮");
            } else {
                property.put("f2", "带实名邮箱");
            }
            property.put("f3", "男");
            property.put("f4", "实名是本人");

        }
        if (Objects.equals("英雄联盟", accountInfo.getType())) {
            params.put("game_id", 841);
            JSONObject jsonObject = JSONObject.parseObject(LDConstant.lol);
            String data = jsonObject.getString("data");
            List<JSONObject> jsonObjects = JSONObject.parseArray(data, JSONObject.class);
            for (JSONObject object : jsonObjects) {
                String name = object.getString("name");
                if (Objects.equals(name, regional)) {
                    String servers = object.getString("servers");
                    List<JSONObject> serversList = JSONObject.parseArray(servers, JSONObject.class);
                    for (JSONObject server : serversList) {
                        String name1 = server.getString("name");
                        if (regional.equals(name1)) {
                            String id = server.getString("id");
                            params.put("server_id", id);
                        }
                    }
                }
            }
            property.put("f1", "当前赛季无排位");

            property.put("f2", "当前赛季无排位");
            property.put("f3", "当前赛季无排位");
            property.put("f4", "QQ等级");
            property.put("f5", "有QQ好友");
            property.put("f6", "30");
            property.put("f7", accountInfo.getHeroes());
            property.put("f8", accountInfo.getSkins());
        }
        BigDecimal bigDecimal = commonApi.addPrice(accountInfo.getPrice(), salePartner.getSeleep());
        commonApi.setPrice(bigDecimal, accountInfo.getId(), salePartner);
        params.put("price", bigDecimal.setScale(BigDecimal.ROUND_UP, 0));
        String des = accountInfo.getDes();
        if (des.length() > 200) {
            des = des.substring(0, 200);
        }
        params.put("title", descTitle + "||" + accountInfo.getId() + accountInfo.getRegional() + " " + accountInfo.getLevel() + des);
        params.put("description", descTitle + "||" + accountInfo.getId() + accountInfo.getRegional() + " " + accountInfo.getLevel() + accountInfo.getDes());


        InfoImg infoImg = new InfoImg();
        infoImg.setInfoId(accountInfo.getId());
        infoImg.setType(Constants.STR_1);
        List<InfoImg> infoImgs = infoImgMapper.selectInfoImgList(infoImg);
        String imgs = "";
        if (!CollectionUtils.isEmpty(infoImgs)) {
            imgs = infoImgs.stream().map(i -> i.getImgUrl()).collect(Collectors.joining(","));
        }
        if (StringUtils.isEmpty(imgs)) {
            imgs = salePartner.getTwoOther();
        }
        params.put("image", imgs);
        params.put("property", property);
        return params;
    }


    @Override
    public AjaxResult delGame(AccountInfo accountInfo, Long userId, SalePartner sa) {
        String rand_str = rand_str();
        Map<String, Object> params = new LinkedHashMap<>();
        params.put("appid", sa.getSaleKey());
        params.put("secret", sa.getOther());
        params.put("rand_str", rand_str);
        params.put("timestamp", new Date().getTime() / 1000);
        String cover = MapUntils.getCover(params);
        cover = cover.substring(0, cover.length() - 1);
        log.info("cover={}", cover);
        String sign = DigestUtils.md5Hex(cover);
        String sr = sign + rand_str;
        try {
            sr = SecuritySHA1Utils.shaEncode(sr);
        } catch (Exception e) {
            e.printStackTrace();
        }
        params.put("sign", sr);

        params.put("id", accountInfo.getLdvt());
        params.put("code", accountInfo.getId());
        String path = "api/goods/platform/under";

        log.info("老达删除接口请求参数={}", JSONObject.toJSONString(params));
        String response = HttpUtils.doPostForm(sa.getTwoOther() + path, params, null);
        if (StringUtils.isEmpty(response)) {
            throw new GlobalException("请求接口失败");
        }
        log.info("老达删除接口返回参数={}", JSONObject.toJSONString(response));
        JSONObject resultJson = JSONObject.parseObject(response);
        Map<String, Object> result = new HashMap<>();

        if (!"1".equals(resultJson.getString("code"))) {
            result.put("code", 500);
        } else {
            result.put("code", 200);
            AccountInfo info = accountInfoMapper.selectAccountInfoById(accountInfo.getId());
            info.setLdvt(null);
            accountInfoMapper.updateAccountInfo(info);
        }

        result.put("req", JSONObject.toJSONString(params));
        result.put("res", response);
        result.put("msg", resultJson.getString("data"));
        return AjaxResult.success(result);
    }


    private String rand_str() {

        long time = new Date().getTime();
        String s = String.valueOf(time);
        s = s.substring(7, s.length());
        return s;
    }


    public static void main(String[] args) {

        long time = new Date().getTime();
        String s = String.valueOf(time);
        String rand_str = "574159";

        String ss = "appid=xiaoyangren&secret=wrU8RKG18KDnzmjbpagVDpUOzdsix8&rand_str=574159&timestamp=1677918574";

        Map<String, Object> params = new LinkedHashMap<>();
        params.put("appid", "xiaoyangren");
        params.put("secret", "wrU8RKG18KDnzmjbpagVDpUOzdsix8");
        params.put("rand_str", rand_str);
        params.put("timestamp", "1677918574");
        String cover = MapUntils.getCover(params);
        cover = cover.substring(0, cover.length() - 1);
        log.info("cover={}", cover);
        String sign = DigestUtils.md5Hex(cover);
        String sr = sign + rand_str;
        log.info("sr={}", sr);
        try {
            sr = SecuritySHA1Utils.shaEncode(sr);
        } catch (Exception e) {
            e.printStackTrace();
        }
        log.info("sign={}", sign);
        log.info("sr={}", sr);
        params.put("sign", sr);
        String baseUrl = "http://api.dev.ldds.com/";
//        String urlGames = "api/goods/platform/servers";
        String urlGames = "api/goods/platform/property";

        params.put("game_id", "813");
        System.out.println(JSONObject.toJSONString(params));
        String response = HttpUtils.doPostForm(baseUrl + urlGames, params, null);

        System.out.println(response);

        //获取所有游戏
        //{"code":1,"msg":"成功","time":1677920839,"data":[{"id":95464,"name":"绝地求生"},{"id":204,"name":"和平精英"},{"id":663,"name":"王者荣耀"},{"id":813,"name":"永劫无间"},{"id":59,"name":"穿越火线"},{"id":809,"name":"原神"},{"id":95467,"name":"APEX英雄"},{"id":841,"name":"英雄联盟"}]}
        //{"code":1,"msg":"成功","time":1677921504,"data":[{"id":664,"name":"王者荣耀安卓版","servers":[{"id":70582,"name":"QQ"},{"id":71058,"name":"微信"}]},{"id":665,"name":"王者荣耀苹果版","servers":[{"id":71402,"name":"QQ"},{"id":71536,"name":"微信"}]}]}
        //{"code":1,"msg":"成功","time":1677921643,"data":[{"id":205,"name":"和平精英安卓版","servers":[{"id":23401,"name":"QQ"},{"id":23404,"name":"微信"}]},{"id":206,"name":"和平精英IOS版","servers":[{"id":23407,"name":"QQ"},{"id":23410,"name":"微信"}]}]}
        //{"code":1,"msg":"成功","time":1677930227,"data":[{"id":95523,"name":"网通区","servers":[{"id":95545,"name":"巨龙之巢"},{"id":95546,"name":"扭曲丛林"},{"id":95547,"name":"恕瑞玛"},{"id":95548,"name":"无畏先锋"},{"id":95549,"name":"弗雷尔卓德"},{"id":95550,"name":"德玛西亚"},{"id":95551,"name":"比尔吉沃特"}]},{"id":95524,"name":"全网络大区","servers":[{"id":95554,"name":"男爵领域"},{"id":95553,"name":"峡谷之巅"}]},{"id":95525,"name":"其他","servers":[{"id":95552,"name":"教育网专区"}]},{"id":95522,"name":"电信区","servers":[{"id":95541,"name":"钢铁烈阳"},{"id":95542,"name":"裁决之地"},{"id":95543,"name":"班德尔城"},{"id":95544,"name":"暗影岛"},{"id":95540,"name":"黑色玫瑰"},{"id":95539,"name":"祖安"},{"id":95538,"name":"诺克萨斯"},{"id":95537,"name":"皮尔特沃夫"},{"id":95536,"name":"战争学院"},{"id":95535,"name":"巨神峰"},{"id":95534,"name":"雷瑟守备"},{"id":95533,"name":"水晶之痕"},{"id":95532,"name":"均衡教派"},{"id":95531,"name":"艾欧尼亚"},{"id":95530,"name":"守望之海"},{"id":95529,"name":"征服之海"},{"id":95528,"name":"卡拉曼达"},{"id":95527,"name":"皮城警备"},{"id":95526,"name":"影流"}]}]}
    }

}
